package com.lovo.project.servlet.user;
import com.lovo.project.enums.UserCodeEnum;
import com.lovo.project.exception.OurException;
import com.lovo.project.model.UserDO;
import com.lovo.project.service.UserService;
import com.lovo.project.service.impl.UserServiceImpl;
import com.lovo.project.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UserLoginServlet",urlPatterns = "/user/login")
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("userName");
        String passWord = request.getParameter("userPwd");
        PrintWriter out = response.getWriter();
        try {
            UserDO login = userService.login(userName, passWord);
            request.getSession().setAttribute("loginUser",login);
            out.print(ResultVO.success().add(login).toJson());
        } catch (OurException e) {
            out.print(ResultVO.fail(e.getCodeEnum()).toJson());
        }catch (Exception e1){
            out.print(ResultVO.fail(UserCodeEnum.USER_UNKNOWN_ERROR).toJson());
        }finally {
            out.close();
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
